package com.eliza.v.http.resp

import io.vertx.core.Vertx
import io.vertx.core.buffer.Buffer
import io.vertx.core.impl.VertxInternal
import java.awt.Color
import java.awt.image.BufferedImage
import java.io.ByteArrayOutputStream
import java.io.IOException
import javax.imageio.ImageIO


class Image(vertx: Vertx, name: String?) {
    val colorMap: MutableMap<Int, Buffer> = HashMap<Int, Buffer>()
    private var width = 0
    private var height = 0
    private val data: IntArray

    init {
        try {
            val raster = ImageIO.read((vertx as VertxInternal).resolveFile(name))
            width = raster.width
            height = raster.height
            data = raster.getRGB(0, 0, width, height, null, 0, width)
            for (pixel in data) if (!colorMap.containsKey(pixel)) {
                val offlineImage = BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB)
                val g2 = offlineImage.createGraphics()
                g2.paint = Color(pixel, true)
                g2.fillRect(0, 0, 1, 1)
                val out = ByteArrayOutputStream()
                ImageIO.write(offlineImage, "PNG", out)
                colorMap[pixel] = Buffer.buffer().appendBytes(out.toByteArray())
                out.close()
                g2.dispose()
            }
        } catch (e: IOException) {
            throw RuntimeException(e)
        }
    }

    fun generateHTML(sz: Int): Buffer {
        val buffer: Buffer = Buffer.buffer()
        buffer.appendString("<!DOCTYPE html>")
        buffer.appendString("<html>")
        buffer.appendString("<head>")
        buffer.appendString("<title>H2 test</title>")
        buffer.appendString(
            "<style>" +
                    "#wrap { width:" + width * sz + "px; height:" + height * sz + "px };" +
                    ".row { width:" + width * sz + "px }" +
                    "img { margin:0; padding:0; border:none; float:left; width: " + sz + "px; height: " + sz + "px }" +
                    "</style>"
        )
        buffer.appendString("</head>")
        buffer.appendString("<body><div id=\"wrap\">")
        for (i in 0 until height) {
            buffer.appendString("<div class=\"row\">")
            for (j in 0 until width) {
                buffer.appendString("<img src=\"/img/$j/$i\">")
            }
            buffer.appendString("</div>")
        }
        buffer.appendString("</div></body>")
        buffer.appendString("</html>")
        return buffer
    }

    fun getPixel(x: Int, y: Int): Buffer? {
        return colorMap[data[y * width + x]]
    }
}